package com.lagou.rpc.consumer.zk;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定时上报线程
 *
 * @Author: zhangzhiwei
 * @Date: 2022/2/15 22:01
 */
public class ReportThread implements Runnable {

    private CuratorFramework zkClient;

    public ReportThread(CuratorFramework zkClient){
        this.zkClient = zkClient;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (true) {
            try {
                System.out.println("========定时上报线程更新节点开始！========");
                ConcurrentHashMap<String, String> map = RequestMsgContainer.getMap();

                // 1.获取所有的子节点
                List<String> strings = zkClient.getChildren().forPath("/provider");
                for (String s : strings) {
                    String path = "/provider/" + s;
                    // 2.获取子节点的内容
                    byte[] bytes = zkClient.getData().forPath(path);
                    String nodeData = new String(bytes);
                    JSONObject nodeJsonObject = JSONObject.parseObject(nodeData);
                    // 3.查看map中是否存放该子节点的请求
                    String jsonStr = map.get(path);
                    if (jsonStr != null) {
                        // 3.1如果存在，则更新子节点内容
                        JSONObject strJsonObject = JSONObject.parseObject(jsonStr);
                        nodeJsonObject.put("usedTime", strJsonObject.get("usedTime"));
                        nodeJsonObject.put("requestTime", strJsonObject.get("requestTime"));
                        zkClient.setData().forPath(path, nodeJsonObject.toJSONString().getBytes());
                        System.out.println(path + "更新节点成功");
                    } else {
                        // 3.2如果不存在，继续判断该子节点内容的最后一次请求是否失效(超过5秒)
                        long requestTime = Long.parseLong(String.valueOf(nodeJsonObject.get("requestTime")));
                        long curTime = System.currentTimeMillis();
                        if (requestTime != 0 && curTime - requestTime > 5000) {
                            // 3.2.1如果失效了，那么清除最后一次请求耗时和时间
                            nodeJsonObject.put("usedTime", 0);
                            nodeJsonObject.put("requestTime", 0);
                            zkClient.setData().forPath(path, nodeJsonObject.toJSONString().getBytes());
                            System.out.println(path + "最后一次请求超过5秒，失效");
                        }
                    }
                }
                System.out.println("========定时上报线程更新节点完毕！========");
                map.clear();
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
